//
//  BCProjectsController.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/11/15.
//  Copyright © 2018年 guoshikeji. All rights reserved.
//

#import "BCProjectsController.h"
//
#import "BCProjectDetailsController.h"


//refresh
#import "BCRefreshNormalHeader.h"
#import "BCRefreshAutoFooter.h"

//cell
#import "BCMyProjectCell.h"

//request
#import "UserIndustryRequest.h"//请求数据

@interface BCProjectsController () <UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UITableView *projectTable;

/**
 *refreshHeader
 */
@property (nonatomic, strong) BCRefreshNormalHeader *refreshHeader;

/**
 *refreshAutoFooter
 */
@property (nonatomic, strong) BCRefreshAutoFooter *refreshAutoFooter;

/**
 *projectSource
 */
@property (nonatomic, strong) NSMutableArray *projectSource;


/**
 *page 请求的页面
 */
@property (nonatomic, assign) NSInteger reqeustPage;

@end

@implementation BCProjectsController

- (NSMutableArray *)projectSource {
    if (!_projectSource) {
        _projectSource = [NSMutableArray array];
    }
    return _projectSource;
}

- (BCRefreshNormalHeader *)refreshHeader {
    if (!_refreshHeader) {
        _refreshHeader = [BCRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshHeaderAction)];
    }
    return _refreshHeader;
}

- (BCRefreshAutoFooter *)refreshAutoFooter {
    if (!_refreshAutoFooter) {
        _refreshAutoFooter = [BCRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshAutoFooterLoadMoreAction) needBottomSafeArea:true];
    }
    return _refreshAutoFooter;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //
    [self setupSubviews];
    //请求数据
    [self requestUserIndustryInit:true refresh:false loadMore:false];
}

- (void)setupSubviews {
    self.projectTable = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.projectTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.projectTable.dataSource = self;
    self.projectTable.delegate = self;
    [self.view addSubview:self.projectTable];
    [self.projectTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.customNaviBar.mas_bottom);
        make.left.bottom.right.mas_equalTo(self.view);
    }];
    [self.projectTable registerClass:BCMyProjectCell.class forCellReuseIdentifier:NSStringFromClass(BCMyProjectCell.class)];
    //
    [self.projectTable setMj_header:self.refreshHeader];
    //
    [self.view layoutIfNeeded];
}



#pragma mark - UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.projectSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UserIndustryDataModel *cellData = self.projectSource[indexPath.row];
    BCMyProjectCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(BCMyProjectCell.class)];
    cell.cellData = cellData;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    UserIndustryDataModel *cellData = self.projectSource[indexPath.row];
    return [tableView fd_heightForCellWithIdentifier:NSStringFromClass(BCMyProjectCell.class) configuration:^(id cell) {
        ((BCMyProjectCell *)cell).cellData = cellData;
    }];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UserIndustryDataModel *cellData = self.projectSource[indexPath.row];
    if (cellData) {
        [self toProjectDetailsAction:cellData];
    }
}


#pragma mark - refreshHeaderAction
- (void)refreshHeaderAction {
    [self.projectTable bc_hiddenError];
    [self requestUserIndustryInit:false refresh:true loadMore:false];
}
//loadMore
- (void)refreshAutoFooterLoadMoreAction {
    //
    [self requestUserIndustryInit:false refresh:false loadMore:true];
}


#pragma mark - request
/**
 请求数据
 */
- (void)requestUserIndustryInit:(BOOL)init refresh:(BOOL)refresh loadMore:(BOOL)loadMore {
    if (init) {
        [self.view bc_showLoadingInsets:UIEdgeInsetsMake(CGRectGetHeight(self.customNaviBar.frame), 0, 0, 0)];
    }
    if (init||refresh) {
        if (self.projectTable.mj_footer) {
            [self.projectTable setMj_footer:nil];
        }
        if (_refreshAutoFooter) {
            [_refreshAutoFooter resetNoMoreData];
        }
    }
    UserIndustryRequest *request = [UserIndustryRequest new];
    if (init||refresh) {
        self.reqeustPage = 1;
        request.page = [NSString stringWithFormat:@"%@",@(self.reqeustPage)];
    }
    if (loadMore) {
        request.page = [NSString stringWithFormat:@"%@",@(self.reqeustPage+1)];;
    }
    //
    WEAK_SELF
    [request didRequestCompleted:^{
        if (init) {
            [wself.view bc_hiddenLoading];
        }
        if (refresh) {
            [wself.refreshHeader endRefreshing];
        }
        if (loadMore) {
            [wself.refreshAutoFooter endRefreshing];
        }
    }];
    [request didRequestSuccessed:^(id result, id page) {
        wself.reqeustPage = request.page.integerValue;
        //
        UserIndustryResponse *resp = result;
        [wself handleResponseData:resp.data init:init refresh:refresh loadMore:loadMore];
    }];
    [request didRequestFailed:^(NSError *error) {
        if (error&&wself.view) {
            NSString *errMsg = error.domain;
            [QMUITips showError:errMsg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:errMsg]];
            if (init) {
                [wself.projectTable bc_showError:error needRefresh:true refreshTitle:nil target:wself refreshAction:@selector(requestInitErrorAction)];
            }
        }
    }];
    [request requestServer];
}
- (void)requestInitErrorAction {
    [self.projectTable bc_hiddenError];
    [self requestUserIndustryInit:true refresh:false loadMore:false];
}
//
- (void)handleResponseData:(UserIndustryData *)data init:(BOOL)init refresh:(BOOL)refresh loadMore:(BOOL)loadMore {
    //做保护 可能在加载更多时 操作了刷新 那么此次加载更多数据不要直接舍弃
    if (loadMore) {
        if (!self.projectTable.mj_footer) {
            return;
        }
    }
    //
    if (data) {
        //设置title
        /**
         加入购买总数
         */
        NSString *title = data.flow.title;
        NSInteger total = data.data.total;
        if (total>0) {
            title = [title stringByAppendingFormat:@"(%@)",@(total)];
        }
        self.title = title;
        //处理数据
        NSArray *dataSource = data.data.data;
        if (init||refresh) {
            [self.projectSource removeAllObjects];
            //
            if (dataSource.count==0) {
                [self.projectTable bc_showEmptyDataText:data.data.text.not_data detail:nil];
            }else {
                [self.refreshAutoFooter setTitle:data.data.text.bottom forState:MJRefreshStateNoMoreData];
                if (data.more) {
                    //加入加载更多控件
                    [self.projectTable setMj_footer:self.refreshAutoFooter];
                }else {//可以再次显示没有更多
                    
                }
            }
        }
        if (loadMore) {
            if (!data.more) {
                //显示咩有更多了
                [self.refreshAutoFooter endRefreshingWithNoMoreData];
            }
        }
        
        UserIndustryDataText *dataText = data.data.text;
        for (int i=0; i<dataSource.count; i++) {
            UserIndustryDataModel *model = dataSource[i];
            model.dataText = dataText;
            [self.projectSource addObject:model];
        }
        
    }
    [self.projectTable reloadData];
}




//项目明细
- (void)toProjectDetailsAction:(UserIndustryDataModel *)model {
    BCProjectDetailsController *detail = [BCProjectDetailsController new];
    detail.projectId = model.project_id;
    [self.navigationController pushViewController:detail animated:true];
}

@end
